import { useEffect, useRef, useState } from "react";
import type { MouseEvent } from "react";
import type { FC, ReactNode } from "react";
export type PopoverPosition =
  | "top"
  | "bottom"
  | "left"
  | "right"
  | "top-left"
  | "top-right"
  | "bottom-left"
  | "bottom-right"
  | "context-menu";

interface PopoverProps {
  isOpen: boolean;
  onClose: () => void;
  triggerRef: React.RefObject<HTMLButtonElement | HTMLElement>;
  position?: PopoverPosition;
  children: ReactNode;
  className?: string;
  contextMenuPosition?: { x: number; y: number };
}

const Popover: FC<PopoverProps> = ({
  isOpen,
  onClose,
  triggerRef,
  position = "bottom",
  children,
  className = "",
  contextMenuPosition,
}) => {
  const popoverRef = useRef<HTMLDivElement>(null);
  const [popoverStyle, setPopoverStyle] = useState<React.CSSProperties>({});

  // 计算位置
  const calculatePosition = () => {
    if (!popoverRef.current) return;

    // 如果是右键菜单特殊位置且有坐标信息
    if (position === "context-menu" && contextMenuPosition) {
      const popoverRect = popoverRef.current.getBoundingClientRect();
      const spacing = 2; // 右键菜单间距更小
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      // 默认尝试在鼠标位置右下方显示
      let top = contextMenuPosition.y + spacing;
      let left = contextMenuPosition.x;

      // 边界校正
      if (left + popoverRect.width > windowWidth) {
        left = contextMenuPosition.x - popoverRect.width; // 如果右侧空间不足，改为左侧显示
        if (left < 0) left = 0; // 如果左侧也不行，则贴左边缘
      }

      if (top + popoverRect.height > windowHeight) {
        top = contextMenuPosition.y - popoverRect.height; // 如果下方空间不足，改为上方显示
        if (top < 0) top = 0; // 如果上方也不行，则贴上边缘
      }

      setPopoverStyle({
        position: "fixed",
        top: `${top}px`,
        left: `${left}px`,
        zIndex: 50,
      });

      return;
    }

    if (!triggerRef.current) return;

    const triggerRect = triggerRef.current.getBoundingClientRect();
    const popoverRect = popoverRef.current.getBoundingClientRect();

    const spacing = 8; // 设置一些间距
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    let top = 0;
    let left = 0;

    // 这里输出调试信息
    console.log("Popover position:", position);
    console.log("Trigger rect:", triggerRect);
    console.log("Popover rect:", popoverRect);

    switch (position) {
      case "top":
        top = triggerRect.top - popoverRect.height - spacing;
        left = triggerRect.left + triggerRect.width / 2 - popoverRect.width / 2;
        console.log("Setting top position:", top, left);
        break;
      case "bottom":
        top = triggerRect.bottom + spacing;
        left = triggerRect.left + triggerRect.width / 2 - popoverRect.width / 2;
        break;
      case "left":
        top = triggerRect.top + triggerRect.height / 2 - popoverRect.height / 2;
        left = triggerRect.left - popoverRect.width - spacing;
        break;
      case "right":
        top = triggerRect.top + triggerRect.height / 2 - popoverRect.height / 2;
        left = triggerRect.right + spacing;
        break;
      case "top-left":
        top = triggerRect.top - popoverRect.height - spacing;
        left = triggerRect.left;
        break;
      case "top-right":
        top = triggerRect.top - popoverRect.height - spacing;
        left = triggerRect.right - popoverRect.width;
        break;
      case "bottom-left":
        top = triggerRect.bottom + spacing;
        left = triggerRect.left;
        break;
      case "bottom-right":
        top = triggerRect.bottom + spacing;
        left = triggerRect.left + triggerRect.width - popoverRect.width;
        if (left < triggerRect.left) {
          left = triggerRect.left;
        }
        break;
      default:
        top = triggerRect.bottom + spacing;
        left = triggerRect.left + triggerRect.width / 2 - popoverRect.width / 2;
    }

    // 边界校正
    if (left < 0) left = spacing;
    if (left + popoverRect.width > windowWidth)
      left = windowWidth - popoverRect.width - spacing;
    if (top < 0) top = spacing;
    if (top + popoverRect.height > windowHeight)
      top = windowHeight - popoverRect.height - spacing;

    // 确保弹出层的位置设置正确
    console.log("Final position:", { top, left });
    setPopoverStyle({
      position: "fixed",
      top: `${top}px`,
      left: `${left}px`,
      zIndex: 50,
      maxWidth: "100vw",
      maxHeight: "calc(100vh - 20px)",
    });
  };

  // 监听点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        popoverRef.current &&
        !popoverRef.current.contains(event.target as Node) &&
        triggerRef.current &&
        !triggerRef.current.contains(event.target as Node)
      ) {
        onClose();
      }
    };

    if (isOpen) {
      // 设置一个短暂延迟确保DOM已经更新
      setTimeout(calculatePosition, 10);
      document.addEventListener("mousedown", handleClickOutside);
      window.addEventListener("resize", calculatePosition);
      window.addEventListener("scroll", calculatePosition);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      window.removeEventListener("resize", calculatePosition);
      window.removeEventListener("scroll", calculatePosition);
    };
  }, [isOpen, onClose, triggerRef, position]);

  if (!isOpen) return null;

  return (
    <div
      ref={popoverRef}
      style={popoverStyle}
      className={`bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 ${className}`}
      data-position={position} // 添加这个属性方便调试
    >
      {children}
    </div>
  );
};

export default Popover;
